package itsm.isperp.framework.sequence;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.domain.IBean;

import java.lang.reflect.Field;
import java.util.Set;

import javax.persistence.Table;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2014-3-2
 * @since 1.0
 * 
 */
public class SequenceUtils {

	// /**
	// * 生成流水号
	// *
	// * @param entity
	// */
	// public static void genericSequence(IBean entity) {
	// genericSequenceAndGetField(entity);
	// }

	/**
	 * 生成流水号
	 * 
	 * @param entity
	 * @param set
	 */
	public static void genericSequence(IBean entity, Set<String> set) {
	 
		String fname = genericSequenceAndGetField(entity);
		if (fname != null && set != null && !set.contains(fname))
			set.add(fname);
	}

	private static String genericSequenceAndGetField(IBean entity) {

		String codeColumn = null;
		String fname = null;

		Class<? extends IBean> clazz = entity.getClass();
		Table table = clazz.getAnnotation(Table.class);
		if (table != null) {

			if (SequenceGenerator.getRule(table.name()) != null) {

				codeColumn = SequenceGenerator.getRule(table.name())
						.getColumnName();
				fname = itsm.isperp.framework.utils.StringUtils
						.camelCaseWord(codeColumn);
				Field field = ReflectionUtils.findField(entity.getClass(),
						fname);
				field.setAccessible(true);
				Object v = ReflectionUtils.getField(field, entity);
				if (v == null || StringUtils.isBlank(v.toString())) {

					SequenceGenerator sg = ContextHolder
							.getSpringBean("sequenceGenerator");
					String seq = sg.next(table.name());
					if (seq != null) {
						try {
							field.set(entity, seq);
						} catch (Exception e) {
							return null;
						}
						return fname;
					}
				}

			}

		}

		return null;

	}
}
